#!/usr/bin/env bash

set -e

REPO_OWNER="yetone"
REPO_NAME="avante.nvim"
RELEASE_VERSION="v0.0.27"  # Hardcoded version to avoid API calls

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
TARGET_DIR="${SCRIPT_DIR}/build"

# Platform detection
case "$(uname -s)" in
Linux*)  PLATFORM="linux" LIB_EXT="so" ;;
Darwin*) PLATFORM="darwin" LIB_EXT="dylib" ;;
*)       echo "Unsupported platform"; exit 1 ;;
esac

# Architecture detection
case "$(uname -m)" in
x86_64)  ARCH="x86_64" ;;
aarch64|arm64) ARCH="aarch64" ;;
*)       echo "Unsupported architecture"; exit 1 ;;
esac

LUA_VERSION="${LUA_VERSION:-luajit}"
ARTIFACT_NAME="avante_lib-${PLATFORM}-${ARCH}-${LUA_VERSION}.tar.gz"
DOWNLOAD_URL="https://githubfast.com/${REPO_OWNER}/${REPO_NAME}/releases/download/${RELEASE_VERSION}/${ARTIFACT_NAME}"

# Create target directory if needed
mkdir -p "$TARGET_DIR"

echo "Downloading ${ARTIFACT_NAME} from githubfast.com..."
if curl -Lf "$DOWNLOAD_URL" | tar -zxv -C "$TARGET_DIR"; then
    echo "$RELEASE_VERSION" > "${TARGET_DIR}/.tag"
    echo "Successfully downloaded and extracted ${ARTIFACT_NAME}"
else
    echo "Download failed, building from source..."
    cargo build --release --features="$LUA_VERSION"
    for f in target/release/lib*.$LIB_EXT; do
        cp "$f" "${TARGET_DIR}/$(basename "$f")"
    done
fi
